﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QqForm
{
    public partial class Logining : Form
    {
        private TcpClass tcpClass;
        private Thread thread;

        delegate void InitialForms();

        public Logining()
        {
            InitializeComponent();
            lb_msg.Text = @"正在登录中....";
            thread = new Thread(new ThreadStart(Initial)) { IsBackground = true };
            thread.Start();
        }

        public void Initial()
        {
            tcpClass = new TcpClass();
            bool isSucConn = tcpClass.Connection();
            if (!isSucConn)
            {
                MessageBox.Show(@"连接服务器失败,请检查网络！");
                Invoke(new InitialForms(CloseForms), new object[] { });
                return;
            }
            tcpClass.messageHelper += new TcpClass.MessageHelper(tcp_messageHelper);
            QqCommand qqHelper = new QqCommand();
            qqHelper.LoginSendCommand(tcpClass);
        }

        private void CloseForms()
        {
            tcpClass.Close();
            tcpClass = null;
            Login fm = new Login();
            fm.Show();
            this.Close();
        }

        void tcp_messageHelper(byte[] msg)
        {
            Invoke(new TcpClass.MessageHelper(ShowMessage), new object[] { msg });
        }

        private void ShowMessage(byte[] msg)
        {
            string cmd = Encoding.UTF8.GetString(msg, 0, msg.Length);
            string[] data = cmd.Split('&');
            if (data[1] != "CMD=VERIFYCODE")
            {
                
                Hide();
                return;
            }
            if (data[1] != "CMD=Login")
            {
                return;

            }
            PostQqServerBackResult postQqServerBackResult = (PostQqServerBackResult)new MessageLoginDeal().ShowMessage(tcpClass, msg);
            if (!postQqServerBackResult.IsSuc)
            {
                MessageBox.Show(@"登陆失败:" + postQqServerBackResult.Result);
                return;
            }
            QqMainList mainList = new QqMainList(tcpClass);
            mainList.Show();
            this.Hide();
        }

    }
}
